package com.centling;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		/*
		 * 往客户端增加cookie
		 */
		for(int i =0 ;i <3 ; i++){
			
			Cookie cookie = new Cookie("Short-cookieName"+i,"Short-cookieValue"+i);
			cookie.setMaxAge(-1);//关闭浏览器就失效
			resp.addCookie(cookie);
			
			Cookie cookie2 = new Cookie("Persistence-cookieName"+i,"Persistence-cookieValue"+i);
			cookie2.setMaxAge(3600);//有效期3600秒
			resp.addCookie(cookie2);
		}
		
		/*
		 * 一个servlet/jsp设置的cookie只能被同一个路径或者子路径下面的servlet/jsp读到
		 * 注意此处的路径，不是自愿路径，而是url，
		 * 例如http://localhost:8080/servlet_jsp0100/servlet/hellocookie
		 * 路径下写入的cookie，只能被/servlet/hellocookie或者/servlet路径下的子路径读到
		 */
		
		/*
		 * 读取客户端的所有cookie
		 */
		resp.setContentType("text/html");
		PrintWriter writer = resp.getWriter();
		/*
		 * 注意，此处只能获取本域名(localhost)下的cookie
		 * 其他域名，如www.baidu.com之类的获取不了
		 * 这是由浏览器的安全性决定的
		 */
		writer.write("<table border=\"2\">");
		Cookie[] cookies = req.getCookies();
		if(cookies!=null){
			for(Cookie e : cookies){
				writer.write("<tr>");
				writer.write("<td>");
				writer.write(e.getName());
				writer.write("</td>");
				writer.write("<td>");
				writer.write(e.getValue());
				writer.write("</td>");
				writer.write("</tr>");
			}
		}
		writer.write("</table>");
	}

	
	
}
